/* Copyright 2007 Gearbox Software - http://www.gearboxsoft.com
 
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 
     http:www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.*/
namespace GearBlog.Web.Controllers
{
	using Castle.Components.Validator;
	using Castle.MonoRail.ActiveRecordSupport;
	using Castle.MonoRail.Framework;
	using GearBlog.Web.Filters;
	using GearBlog.Web.Models;
	using GearBlog.Web.Utils;

	[Layout("default")]
	[AuthenticationFilter(typeof(FormsAuthenticationAgent), RequiresLogin = false)]
    public class LoginController : ExtendedControllerBase
    {
        public void Show(string returnUrl)
        {

        }
        public void Login(string username, string password, string returnUrl)
        {
            if (!SecurityUtil.Authenticate(this, username, password, false, returnUrl))
            {
                Flash["errorMessage"] = "Incorrect username or password.";
                RedirectToReferrer();
            }
        }
		public void AccessDenied()
		{
			
		}
		public void ShowProfile()
		{
			User user = SecurityUtil.GetCurrentUser(Context);
			if (user!=null)
			{
				PropertyBag["User"] = user;
			}
			else 
				SecurityUtil.ShowAccessDenied(this);
		}
		public void ShowResetPassword()
		{
			
		}
		public void ResetPassword(string userName, string email)
		{
			User user;
			if (!string.IsNullOrEmpty(userName))
				user = User.FindByUserName(userName);
			else
				user = User.FindByEmail(email);

			// reset password and save
			user.Password = RandomStringUtil.Generate(8);
			user.ConfirmPassword = user.Password;

			user.Save();

			// send notification
			PropertyBag["user"] = user;
			PropertyBag["Setting"] = Setting;
			PropertyBag["NewPassword"] = user.Password;

			RenderEmailAndSend("resetpasswordnotify");

			Flash["message"] = "Password reseted successfully. Please check your email to see your new password.";
			RedirectToReferrer();
		}
		//We use current logged in user credential instead of passing Id to prevent user modifying other's password
		public void ChangePassword(string originalPassword, string password, string confirmPassword)
		{
			// validate original password
			User user = CurrentUser;
			if (!user.IsPasswordCorrect(originalPassword))
				RedirectToReferrerWithMessage("Incorrect password, please try again.");
			else
			{
				user.Password = password;
				user.ConfirmPassword = confirmPassword;

				ValidatorRunner runner;
				if (!IsValid(user, out runner, RunWhen.Custom|RunWhen.Everytime))
				{
					Flash["ErrorSummary"] = runner.GetErrorSummary(user);
					RedirectToReferrer();
				}
				else
				{
					user.SetPasswordHash();
					user.Save();

					RedirectToReferrerWithMessage("Password changed successfully.");
				}
			}	

		}
		public void SaveProfile([ARDataBind("User",AutoLoad=AutoLoadBehavior.NullIfInvalidKey)] User user)
		{
			
			//verify user is currect user
			if (user.Id!=CurrentUser.Id)
				RedirectToReferrerWithMessage("User Id not match");
			else
			{
				ValidatorRunner runner;
				if (!IsValid(user, out runner, RunWhen.Everytime))
				{
					Flash["ErrorSummary"] = runner.GetErrorSummary(user);
					RedirectToReferrer();
				}
				else
				{
					user.Save();
					RedirectToReferrerWithMessage("Profile changes saved successfully.");
				}
			}
		}
		private void RedirectToReferrerWithMessage(string message)
		{
			Flash["message"] = message;
			RedirectToReferrer();
		}
        public void Logout()
        {
            SecurityUtil.Logout(this.Context);
            RedirectToReferrer();
        }

    }
}